package lib.bone.admin.controller.nepu;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.lang.Validator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lib.bone.access.config.cycle.NepuCycleService;
import lib.bone.access.constant.UseMethodConst;
import lib.bone.access.constant.WorkloadTypeConst;
import lib.bone.access.module.post.NepuPostService;
import lib.bone.access.module.post.domain.NepuPost;
import lib.bone.audit.domain.vo.PerformanceVO;
import lib.bone.audit.workload.domain.NepuWorkload;
import lib.bone.audit.workload.domain.WorkloadUseLog;
import lib.bone.audit.workload.service.NepuWorkloadService;
import lib.bone.audit.workload.service.WorkloadUseLogService;
import lib.bone.common.constant.ResponseCodeConst;
import lib.bone.common.core.domain.ResponseDTO;
import lib.bone.system.domain.entity.SysUser;
import lib.bone.system.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.text.DecimalFormat;
import java.util.List;
import java.util.Optional;

/**
 * 绩效审计
 * @author kindear
 */
@Slf4j
@RestController
@RequestMapping("nepu")
@Api(tags = "绩效审计")
public class AuditController {
    @Autowired
    NepuWorkloadService workloadService;

    @Autowired
    WorkloadUseLogService logService;

    @Autowired
    NepuCycleService cycleService;

    @Autowired
    SysUserService userService;

    @Autowired
    NepuPostService postService;

    @Autowired
    NepuWorkloadService nepuWorkloadService;

    @Autowired
    DeductionController deductionController;

    @GetMapping("audit/salary")
    @ApiOperation(value = "绩效工资计算")
    public ResponseDTO<Object> auditSalary(@RequestParam(value = "userId",required = false) Long userId,
                                           @RequestParam(value = "cycleId",required = false) String cycleId){
        if (Validator.isEmpty(userId))
            userId = StpUtil.getLoginIdAsLong();

        // 1. 获取用户岗位信息
        Optional<SysUser> userOp = userService.getById(userId);

        if (!userOp.isPresent()) return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND,"用户信息不存在");

        SysUser user = userOp.get();

        String postId = user.getPostId();

        if (Validator.isEmpty(postId)){
            return ResponseDTO.wrap(ResponseCodeConst.FORBIDDEN,"用户未绑定岗位，请先绑定岗位信息");
        }

        Optional<NepuPost> postOp = postService.getById(postId);

        if (!postOp.isPresent()) return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND,"绑定岗位信息不存在");

        NepuPost nepuPost = postOp.get();

        // 获取岗位基本绩效数据
        double standard = nepuPost.getStandard();

        // 获取科研所需工作量
        double rNeed = nepuPost.getResearchWorkload();

        // 获取教学所需工作量
        double tNeed = nepuPost.getTeachWorkload();

        //进行抵扣
        deductionController.deductionx(userId);

        // 2. 获取总冲抵记录 - 根据周期和用户ID
        WorkloadUseLog t = new WorkloadUseLog();
        // 获取当前主周期 ID
        if (Validator.isEmpty(cycleId)){
            cycleId = cycleService.getNowResearchCycleId();
        }
        t.setCycleId(cycleId);
        t.setUserId(userId);

        Example<WorkloadUseLog> example = Example.of(t);

        List<WorkloadUseLog> useLogs = logService.findByExample(example);

        // 冲抵的教学和科研工作量之和
        double rtSum = 0.0;

        // 转化薪酬的教学工作量之和
        double tcSum = 0.0;

        //管理工作量
        double mgSum = 0.0;

        for (WorkloadUseLog ele:useLogs){
            String useMethod = ele.getUseMethod();
            if (useMethod.equals(UseMethodConst.DEDUCT_RESEARCH) || useMethod.equals(UseMethodConst.DEDUCT_TEACH)){
                rtSum = rtSum + ele.getWorkload();
            }else if (useMethod.equals(UseMethodConst.CONVERT_SALARY)){
                log.info("ele:"+ele);
                tcSum = tcSum + ele.getWorkload();
            } else if (useMethod.equals(UseMethodConst.MANAGE_SALARY)) {
                mgSum = mgSum + ele.getWorkload();
            }
        }

        PerformanceVO performanceVO = new PerformanceVO();
        NepuWorkload nepuWorkload = new NepuWorkload();
        nepuWorkload.setParentId(cycleId);
        nepuWorkload.setUserId(userId);
        Example<NepuWorkload> example1 = Example.of(nepuWorkload);
        List<NepuWorkload> list = nepuWorkloadService.finAll(example1);
        double researchA = 0.0;

        double researchB = 0.0;

        double researchC = 0.0;

        double teach = 0.0;

        double manage = 0.0;

        double other = 0.0;

        for (NepuWorkload workload : list) {

            if (workload.getWorkloadType().equals(WorkloadTypeConst.TEACH)){
                teach += workload.getWorkload();
            }else if (workload.getWorkloadType().equals(WorkloadTypeConst.MANAGE)){
                manage += workload.getWorkload();
            }else if (workload.getWorkloadType().equals(WorkloadTypeConst.OTHER)){
                other += workload.getWorkload();
            }
            if (workload.getWorkloadLevel().contains("A")){
                researchA += workload.getWorkload();
            }else if (workload.getWorkloadLevel().contains("B")){
                researchB += workload.getWorkload();
                System.out.println("researchB:"+researchB);
            }else if (workload.getWorkloadLevel().contains("C")){
                researchC += workload.getWorkload();
            }

        }

        //系数
        double sub = rtSum / (rNeed + tNeed);
        System.out.println("sub:"+sub);
        System.out.println("standard:"+standard);
        System.out.println("tcSum:"+tcSum);

        performanceVO.setStandardSalary(sub*standard*10000+(tcSum+mgSum)*40);
        performanceVO.setManage(manage);
        performanceVO.setResearchA(researchA);
        String str = String.format("%.2f",researchB);
        researchB = Double.valueOf(str);
        performanceVO.setResearchB(researchB);
        performanceVO.setResearchC(researchC);
        performanceVO.setTeach(teach);
        performanceVO.setTeachConvertSalary(tcSum * 40);
        performanceVO.setManageConvertSalary(mgSum * 40);
        performanceVO.setOther(other);
        //取消冲抵
        deductionController.userWorkloadDeductionCancel(userId);
        return ResponseDTO.succData(performanceVO);


    }



//    @GetMapping("audit/salary")
//    @ApiOperation(value = "绩效工资计算")
//    public ResponseDTO<Object> auditSalary(@RequestParam(value = "userId",required = false) Long userId,
//                                           @RequestParam(value = "cycleId",required = false) String cycleId){
//        if (Validator.isEmpty(userId))
//            userId = StpUtil.getLoginIdAsLong();
//
//        // 1. 获取用户岗位信息
//        Optional<SysUser> userOp = userService.getById(userId);
//
//        if (!userOp.isPresent()) return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND,"用户信息不存在");
//
//        SysUser user = userOp.get();
//
//        String postId = user.getPostId();
//
//        if (Validator.isEmpty(postId)){
//            return ResponseDTO.wrap(ResponseCodeConst.FORBIDDEN,"用户未绑定岗位，请先绑定岗位信息");
//        }
//
//        Optional<NepuPost> postOp = postService.getById(postId);
//
//        if (!postOp.isPresent()) return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND,"绑定岗位信息不存在");
//
//        NepuPost nepuPost = postOp.get();
//
//        // 获取系数
//        double standard = nepuPost.getStandard();
//
//        // 获取科研所需工作量
//        double rNeed = nepuPost.getResearchWorkload();
//
//        // 获取教学所需工作量
//        double tNeed = nepuPost.getTeachWorkload();
//
//        // 2. 获取总冲抵记录 - 根据周期和用户ID
//        WorkloadUseLog t = new WorkloadUseLog();
//        // 获取当前主周期 ID
//        if (Validator.isEmpty(cycleId)){
//            cycleId = cycleService.getNowResearchCycleId();
//        }
//        t.setCycleId(cycleId);
//        t.setUserId(userId);
//
//        Example<WorkloadUseLog> example = Example.of(t);
//
//        List<WorkloadUseLog> useLogs = logService.findByExample(example);
//
//        // 过滤
////        useLogs = useLogs.stream().filter(ele->{
////            return ele.getUseMethod().equals(UseMethodConst.CONVERT_SALARY);
////        }).collect(Collectors.toList());
//
//        // 冲抵的教学和科研工作量之和
//        double rtSum = 0.0;
//
//        // 转化薪酬的教学工作量之和
//        double tcSum = 0.0;
//
//        //管理工作量
//        double mgSum = 0.0;
//
//        for (WorkloadUseLog ele:useLogs){
//            String useMethod = ele.getUseMethod();
//            if (useMethod.equals(UseMethodConst.DEDUCT_RESEARCH) || useMethod.equals(UseMethodConst.DEDUCT_TEACH)){
//                rtSum = rtSum + ele.getWorkload();
//            }else if (useMethod.equals(UseMethodConst.CONVERT_SALARY)){
//                log.info("ele:"+ele);
//                tcSum = tcSum + ele.getWorkload();
//            } else if (useMethod.equals(UseMethodConst.MANAGE_SALARY)) {
//                mgSum = mgSum + ele.getWorkload();
//            }
//        }
//
//
//
//        SalaryVO salaryVO = new SalaryVO();
//
//        double sub = rtSum / (rNeed + tNeed);
//
//        if (sub > 0.3){
//            salaryVO.setStandardSalary( sub * standard * 10000);
//        }else {
//            salaryVO.setStandardSalary(0);
//            salaryVO.setRemark("未完成30%考核最低要求");
//        }
//        salaryVO.setTeachConvertSalary(tcSum * 40);
//        salaryVO.setManageConvertSalary(mgSum * 40);
//
//        return ResponseDTO.succData(salaryVO);
//    }
}
